package cn.wolfcode.wolf2w.gateway.filter;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.core.exception.ServiceException;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

//防恶意刷新过滤器每个ip对同一个接口在20s内访问次数超过20次判定为恶意刷新
@Component
public class BrushFilter implements GlobalFilter {
    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求路径
        String url= exchange.getRequest().getURI().getPath();
        //请求ip
        String ip = exchange.getRequest().getRemoteAddress().getAddress().toString();
        //拼接key
        String key = RedisKeys.BRUSH.join(url, ip);
        redisService.setNxCacheObject(key,0,RedisKeys.BRUSH.getTime(), TimeUnit.SECONDS);
        Long ret = redisService.incrementCacheObjectValue(key, 1);
        if (ret>20){
            //判定为恶意刷新
//          throw new ServiceException("请勿恶意刷新hhhhhhhhhhh是不是没见过黑社会啊");
            R<Object> r=R.fail(500,"请勿恶意刷新是不是没见过黑社会啊");
            //转JSON
            String jsonString = JSON.toJSONString(r);
            DataBuffer resData = exchange.getResponse().bufferFactory().wrap(jsonString.getBytes(StandardCharsets.UTF_8));
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return exchange.getResponse().writeWith(Mono.just(resData));

        }
        return chain.filter(exchange);
    }

}
